//
//  FindContentViewController.m
//  WNZSSQ
//
//  Created by JDKJ on 2018/12/4.
//  Copyright © 2018年 JDKJ. All rights reserved.
//

#import "FindContentViewController.h"
#import "HXWebView.h"
#import "FindContenView.h"
#import "CommentsTableViewCell.h"
#import "CZQMyMainSharView.h"
#import "DCPageVC.h"
#import "LSYReadPageViewController.h"

@interface FindContentViewController ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>

/**
 //数据源
 */
@property(nonatomic,strong)NSMutableArray *dataArr;


/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;

@property (nonatomic , strong) UIWebView *webView;

/** <#explain#> */
@property (nonatomic , assign) CGFloat webHeight;

@property (nonatomic , weak) FindCommentToolView *commentView;

@end

@implementation FindContentViewController

- (void)loadWebView {
    UIWebView *webView = [[UIWebView alloc] init];
    NSURL *url = [NSURL URLWithString:@"https://baijiahao.baidu.com/s?id=1608749120680497443"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //控制整个功能是否启用。
    manager.enable = NO;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //控制整个功能是否启用。
    manager.enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    /**
     * 监听键盘
     **/
    [NotificationCenter addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self showRightImageWithImageName:@"分享"];
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 1)];
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = NO;
    //预先加载url
    NSURL *url = [NSURL URLWithString:@"https://baijiahao.baidu.com/s?id=1608749120680497443"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    //底部
    FindContenToolView *toolView = [[FindContenToolView alloc]init];
    [self.view addSubview:toolView];
    [toolView.shareBtn addTarget:self action:@selector(rightBtnClick)];
    [toolView.writeBtn addTarget:self action:@selector(comment)];
    [toolView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(adaptTabBar);
        
    }];
    
    [self tableView];
    
    FindCommentToolView *commentView = [[FindCommentToolView alloc]init];
    [self.view addSubview:commentView];
    self.commentView = commentView;
    
    [commentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(50);
        make.height.mas_equalTo(50);
    }];

}






#pragma mark - 懒加载

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        
        _dataArr = [NSMutableArray array];
        
    }
    
    return _dataArr;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        
        UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        tableView.delegate=self;
        
        tableView.dataSource=self;
        
        tableView.backgroundColor = [UIColor clearColor];;
        tableView.estimatedRowHeight = 150;
        tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:tableView];
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.right.top.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view).offset(-adaptTabBar);
            
        }];
        
        //        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册
        [tableView registerClass:[FindContenView class] forCellReuseIdentifier:@"cell1"];

        [tableView registerClass:[CommentsTableViewCell class] forCellReuseIdentifier:@"cell2"];
        
        
        
        _tableView = tableView;
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count + 6;
}

//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    

    if (indexPath.row == 0){
        
        FindContenView *cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        [cell1.startBtn addTarget:self action:@selector(readBook)];
        return  cell1;
        
    }else{
        
        CommentsTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        
        if (indexPath.row%2==0) {
            cell2.contentLable.text = @"香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？";
        }else
        {
            cell2.contentLable.text = @"香菜沐浴露是一种什么样的体验香菜沐浴露是一种什么样的体验？";
        }
        
//        cell2.titleString = cell2.contentLable.text;
        
        return  cell2;
        
    }
    
    
    
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row == 0) {
//        NSLog(@"-----%f" , self.webHeight);
//        return _webView.frame.size.height;
//    }else if (indexPath.row == 1)
//    {
//        return 260;
//    }
//    return 144;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.webHeight > 0 ?self.webHeight :SCREENHEIGHT;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.webView;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当离开某行时，让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //获取到webview的高度
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webHeight = height;
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, SCREENWIDTH, height);
    [self.tableView reloadData];
}

#pragma mark - 开始阅读
-(void)readBook
{

    LSYReadPageViewController *pageView = [[LSYReadPageViewController alloc] init];
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"郭黄之恋"withExtension:@"txt"];
    pageView.resourceURL = fileURL;    //文件位置
    pageView.model = [LSYReadModel getLocalModelWithURL:fileURL];  //阅读模型
//    [self.navigationController pushViewController:pageView animated:YES];
    DCPageVC *vc = [[DCPageVC alloc]init];
    vc.filePath = [[NSBundle mainBundle]pathForResource:@"郭黄之恋.txt" ofType:nil];;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 评论
-(void)comment
{
    
    
    [self.commentView.bottomTF becomeFirstResponder];
    
}

#pragma mark - 分享

-(void)rightBtnClick
{
    WS(weakSelf);
    
    CZQMyMainSharView *shareView = [[CZQMyMainSharView alloc]init];
    [shareView onlyShare];
    [shareView showWithAnimation];
    
    shareView.shareClick = ^(NSInteger index) {
        
        [weakSelf shareBtnClick:index];
        
    };
    
}


#pragma mark - 分享回调
-(void)shareBtnClick:(NSInteger)index
{
    
    if (index == 0) {
        //微信朋友圈
        
        [self shareToPlatform:UMSocialPlatformType_WechatTimeLine];
        
    }else if (index == 1){
        
        //微信好友
        [self shareToPlatform:UMSocialPlatformType_WechatSession];
        
    }
    else if (index == 2){
        
        //5,//qq空间
        [self shareToPlatform:UMSocialPlatformType_Qzone];
        
    }
    else if (index == 3){
        
        //4,//QQ聊天页面
        [self shareToPlatform:UMSocialPlatformType_QQ];
        
    }
    
}

- (void)shareToPlatform:(UMSocialPlatformType)platformType{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"万能追书" descr:@"" thumImage:PlaceHold];
    
    //设置网页地址
    shareObject.webpageUrl = @"htps://www.baidu.com";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    /**
     设置分享
     
     @param data 分享返回信息
     @param error 失败信息
     @param UMSocialPlatformType 分享平台
     */
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            //错误码
            
            NSString *result;
            switch (error.code) {
                case UMSocialPlatformErrorType_Unknow:
                    result = @"未知错误";
                    break;
                case UMSocialPlatformErrorType_NotSupport:
                    result = @"不支持（url scheme 没配置，或者没有配置-ObjC， 或则SDK版本不支持或则客户端版本不支持";
                    break;
                case UMSocialPlatformErrorType_AuthorizeFailed:
                    result = @"授权失败";
                    break;
                case UMSocialPlatformErrorType_ShareFailed:
                    result = @"分享失败";
                    break;
                case UMSocialPlatformErrorType_RequestForUserProfileFailed:
                    result = @"请求用户信息失败";
                    break;
                case UMSocialPlatformErrorType_ShareDataNil:
                    result = @"分享内容为空";
                    break;
                case UMSocialPlatformErrorType_ShareDataTypeIllegal:
                    result = @"分享内容不支持";
                    break;
                case UMSocialPlatformErrorType_CheckUrlSchemaFail:
                    result = @"schemaurl fail";
                    break;
                case UMSocialPlatformErrorType_NotInstall:
                    result = @"应用未安装";
                    break;
                case UMSocialPlatformErrorType_Cancel:
                    result = @"您已取消分享";
                    break;
                case UMSocialPlatformErrorType_NotNetWork:
                    result = @"网络异常";
                    break;
                case UMSocialPlatformErrorType_SourceError:
                    result = @"第三方错误";
                    break;
                case UMSocialPlatformErrorType_ProtocolNotOverride:
                    result = @"对应的    UMSocialPlatformProvider的方法没有实现";
                    break;
                default:
                    break;
            }
            
            [MBProgressHUD showText:result];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}

#pragma mark - 键盘处理
- (void)keyBoardWillShow:(NSNotification *)notice
{
    
    // 取出键盘高度
    CGRect keyboardF = [notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyboardF.size.height;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notice.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    
    
    [UIView animateWithDuration:duration animations:^{
        
        [self.commentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.width.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view).offset(-keyBoardHeight);
            make.height.mas_equalTo(50);
        }];
        
        [self.commentView setNeedsLayout];
        [self.commentView layoutIfNeeded];
    }];
}

-(void)keyBoardWillHide:(NSNotification *)notice
{
    
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notice.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    
    
    [UIView animateWithDuration:duration animations:^{
        [self.commentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.width.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view).offset(50);
            make.height.mas_equalTo(50);
        }];
        [self.commentView setNeedsLayout];
        [self.commentView layoutIfNeeded];
    }];
}



#pragma mark 退出键盘
-(void)tapClick{
    
    [self.view endEditing:YES];
}


- (void)dealloc {
    
    
    
    [NotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [NotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [NotificationCenter removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
